<template>
	<view class="Loin_content">
		<view class="header">
			<view class="kg">
				<image :src="eyelogin?'../../static/image/zh.png':'../../static/image/en.png'" @tap="tapnum" class="eyesstyle"></image>
			</view>
			<image src="../../static/image/login_logo.png" class="login_logo"></image>
			<text class="login_text">{{i18n.logintext}}</text>
			<!-- 用户名 -->
			<view class="input_content haha" :style="i18n.loginnameback"><input type="text" v-model="accountName" :style="i18n.logininput"
				 style="" /></view>

			<!-- 密码 -->
			<view class="input_content haha pad_input password_style" :style="i18n.loginpassback">
				<input :type="eye?'text':'password'" v-model="password" :style="i18n.logininput" />
				<image :src="eye?'../../static/image/openeye.png':'../../static/image/closeeye.png'" @tap="chageEye" class="eyes"></image>
			</view>

			<checkbox-group @change="check_xiaobai" class="xiaobai_check">
				<label>
					<checkbox value="1" color="#FFCC33" style="transform:scale(0.7)" />{{i18n.xiaobai_check}}
				</label>
			</checkbox-group>
			<!-- 登录按钮 -->
			<image class="login_btn" :src="changeColor? i18n.login_btn2: i18n.login_btn1" @tap="login"></image>

			<!-- 忘记密码和注册 -->
			<view class="ext_options">
				<text @tap="setNodeInfo">{{i18n.szjd}}</text>
				<text @tap="pwd">{{i18n.Forgetpassword}}</text>
				<text @tap="importWallet">{{i18n.drqblogin}}</text>

				<text @tap="register">{{i18n.registerlogin}}</text>

			</view>

			<setNodeInfo v-if="isSetNodeInfo" @colseNodeInfoHandler="colseNodeInfoHandler" @setNodeInfoHandler="setNodeInfoHandler"></setNodeInfo>
		</view>
	</view>
</template>

<script>
	import {
		ethers
	} from 'ethers';
	import * as oex from 'oex-web3';
	import CryptoJS from 'crypto-js';
	import Files from '../../common/files.js'

	import setNodeInfo from '../../components/setNodeInfo/setNodeInfo.vue'
	export default {
		data() {
			return {
				accountName: "", //账户名
				password: "", //密码
				check: [],
				changeColor: false,
				eye: false,
				owner: "",
				isSetNodeInfo: false,
				eyelogin: true
			}
		},
		components: {
			setNodeInfo
		},
		computed: {
			changeData() {
				const {
					accountName,
					password
				} = this
				return {
					accountName,
					password
				}
			},
			i18n() {
				return this.$t('user')
			}
		},
		watch: {
			changeData: {
				handler: function(newval, oldval) {
					this.accountName = newval.accountName;
					this.password = newval.password;
					if (this.accountName != "" && this.password != "") {
						this.changeColor = true
					} else {
						this.changeColor = false
					}
				},
				deep: true
			}
		},
		onHide() {
			this.password = "";
			this.accountName = "";
		},
		onLoad() {
			var _this = this
			uni.getStorage({
				key: 'language',
				success(e) {
					console.log(e)
					_this.language = e.data
					if (e.data == 'zh') {
						_this.eyelogin = true
					} else {
						_this.eyelogin = false
					}
				}
			})
		},
		methods: {
			setNodeInfo() {
				//设置接入节点
				this.isSetNodeInfo = true;
			},
			chageEye() {
				this.eye = !this.eye;
			},
			check_xiaobai(e) {
				this.check = e.detail.value;
			},
			register() {
				this.$CommonJS.navigateTo('../register/register')
			},
			async login() {
				//验证参数
				console.log(uni.getStorageSync('nodeInfo'))
				const _this = this;
				if (!this.accountName) {

					this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? '账户名不能为空' : 'Account name cannot be empty');
					return;
				}
				if (!this.accountName) {
					this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? '账户名不能为空' : 'Account name cannot be empty');
					return;
				}
				if (!this.$CommonJS.accountValidate(this.accountName)) {
					this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? '账户名不符合规范' :
						'The account name does not conform to the specification');
					return;
				}
				if (!this.password) {
					this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? '密码不能为空' : 'Password cannot be empty');
					return;
				}
				if (!this.$CommonJS.passwordValidate(this.password)) {
					this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? '密码请输入8-16位数字字母组合' :
						'Please input 8-16 digit alphanumeric combination for password');
					return;
				}
				//读取文件
				const str = uni.getStorageSync(_this.accountName);
				uni.showLoading({
					// title:"登陆中",
					title: _this._i18n.locale == 'zh_CN' ? '登陆中' : 'Landing',
				})
				//查看是否存在这个账号

				oex.utils.setApp();
				let accountName = this.accountName;
				if (this.check.length > 0) {
					//小白账户
					accountName = this.$API.xiaobai + this.accountName;

				}

				var data = await oex.account.getAccountExByName(accountName); //请求参数
				const nodeInfo = uni.getStorageSync('nodeInfo');
				this.$CommonJS.request(nodeInfo, "POST", data).then(res => {
					if (res.data.result == null) {
						//账户不存在
						uni.hideLoading()
						_this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? '账户不存在' : 'Account does not exist');
						return;
					} else {
						//验证私钥是否匹配
						_this.owner = res.data.result.authors[0].owner;
						Files.getFileData(accountName).then(txt => {
							//解密
							var bytes = CryptoJS.AES.decrypt(txt, _this.password);

							const arr = bytes.words.filter(item => {
								return Number(item) < 0
							})

							if (arr.length >= 1) {
								uni.hideLoading()
								_this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? '密码错误' : 'Password error');
								return;
							} else {
								var decryptedData = JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
								const publicKey = decryptedData.publicKey;
								if (publicKey == res.data.result.authors[0].owner) {

									//登录成功
									uni.setStorage({
										key: "account_info",
										data: res.data.result
									})
									//设置登录状态
									uni.setStorage({
										key: "login_status",
										data: true,
										success() {
											uni.hideLoading()
											uni.showToast({
												// title:"登录成功",
												title: _this._i18n.locale == 'zh_CN' ? '登录成功' : 'Login Successful',
											})
											setTimeout(() => {
												uni.redirectTo({
													url: '../index/home',
													animationType: "slide-in-right",
												});
											}, 1000)
										}
									})
								} else {
									uni.hideLoading();
									_this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? '登录失败 公钥不匹配' :
										'Login failure, public key mismatch')
								}
							}
						}).catch(err => {
							console.log(err)
							uni.hideLoading();
							_this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? '读取keystore失败' : 'Failed to read keystore')
						})
					}


				})
			},
			importWallet() {
				this.$CommonJS.navigateTo('../import_wallet/importWallet')
			},
			pwd() {
				const _this = this;
				uni.showActionSheet({
					itemList: [this.i18n.ForgetName,this.i18n.xbzhnameforget, this.i18n.zyyhnameforget],
					success: function(res) {
						console.log(res.tapIndex)
						//找回账户名
						if(res.tapIndex == 0){
						// 	_this.$CommonJS.navigateTo('../password/pwd_setp1')
						_this.$CommonJS.navigateTo('../account_name/account_name')
						// uni.navigateTo({
						// 	url:"../account_name/account_name"
						// })
						}
						else if (res.tapIndex == 1) {
							//小白账户
							_this.$CommonJS.navigateTo('../password/pwd_setp1')
						} else if (res.tapIndex == 2) {
							//专业账户
							_this.$CommonJS.navigateTo('../import_wallet/importWallet?isForgetPwd=' + 0)
						}

					},
					fail: function(res) {
						console.log(res.errMsg);
					}
				});

			},
			colseNodeInfoHandler() {
				this.isSetNodeInfo = false;
			},
			async setNodeInfoHandler(nodeInfo) {
				const _this = this
				console.log(nodeInfo);
				this.isSetNodeInfo = false;
				uni.showLoading({
					title: '设置节点中'
				})
				oex.utils.setProvider(nodeInfo);
				uni.setStorageSync('nodeInfo', nodeInfo)
				if (nodeInfo == uni.getStorageSync('nodeInfo')) {
					uni.hideLoading();
					uni.showToast({
						// title:'节点设置成功'
						title: _this._i18n.locale == 'zh_CN' ? '节点设置成功' : 'Node set successfully',
					})
				}
				console.log(uni.getStorageSync('nodeInfo'))
			},
			tapnum() {
				var _this = this
				this.eyelogin = !this.eyelogin;
				if (_this.eyelogin == false) {
					var _this = this
					uni.removeStorageSync('language');
					uni.setStorage({
						key: 'language',
						data: 'en',
						success: function() {
							console.log('中文');
						}
					});
					var system_info = "zh_CN"
					system_info === 'en' ? system_info = this._i18n.locale = 'zh_CN' : system_info = this._i18n.locale = 'en'
					uni.setStorageSync('system_info', system_info)
					uni.reLaunch({
						url: 'index'
					})
				} else {
					var _this = this
					uni.removeStorageSync('language');
					uni.setStorage({
						key: 'language',
						data: 'zh',
						success: function() {
							console.log('中文');
						}
					});
					var system_info = "en"
					system_info === 'en' ? system_info = this._i18n.locale = 'zh_CN' : system_info = this._i18n.locale = 'en'
					uni.setStorageSync('system_info', system_info)
					uni.reLaunch({
						url: 'index'
					})
				}
				uni.getStorage({
				  key:'language',
				  success(e){
				  console.log(e.data)
						if(e.data=="zh"){
								uni.setStorageSync('i18n_language', 'zh_CN');
						}else{
								uni.setStorageSync('i18n_language', 'en_US');
						}				
				  }
				  })
			}
		}
	}
</script>

<style lang="stylus">
	@import "../../static/stylus/login/login.stylus"
</style>
